<script setup lang="ts">
import {computed, ref, watch} from "vue";
import {joinTeam, quitTeam} from "@/api/team.ts";
import {showFailToast, showSuccessToast} from "vant";
import {userStore} from "@/store/userStore.ts";
import {useRoute,useRouter}  from "vue-router";
const router = useRouter()
const route = useRoute()
const userinfo = userStore().userinfo
const props = defineProps<{
  TeamList: any[]
}>()

const showdetailUser =ref(null)
const showPicker = ref(false);

const detailInfo = (user,team) => {
  showdetailUser.value = user
  showPicker.value = true

}
const show =ref(false)
const JoinTeamRequest ={
  teamId: '',
  password: ''
}

const joinpassword = (id) => {
  show.value = true
  JoinTeamRequest.teamId = id
  console.log("hahahahffefe ")
  console.log(show.value)
}
const join = (id) => {
  JoinTeamRequest.teamId = id
  joinTeam(JoinTeamRequest).then((res)=>{
    if(res.data.data){
      showSuccessToast("加入队伍成功")
      JoinTeamRequest.teamId = ''
      JoinTeamRequest.password = ''
      setTimeout(() => {
        window.location.reload();
      }, 1000)
    }
    else {
      showFailToast(res.data.description)
    }
  }).catch((err)=>{})
  console.log("加入队伍")
}

const  cancel = () => {
  show.value = false
  JoinTeamRequest.teamId = ''
  JoinTeamRequest.password = ''
}

const exitTeamObj = {
  teamId: '',
  specialUserId: ''
}
function exitTeam(Team){
  if(Team == null){
    showFailToast("请选择退出的队伍")
  }
  exitTeamObj.teamId = Team.id
  if(userinfo.id == Team.userId &&Team.userVOList.length >1){
    yjshow.value = true
    if(columns.value.length ==0) {
      Team.userVOList.forEach((item) => {
        if(item.id != userinfo.id)
        columns.value.push({"text":item.userAccount,value: item.id})
      })
    }
    return;
  }
  quitTeam(exitTeamObj).then((res) =>{
    if(res.data.data){
      showSuccessToast("退出队伍成功")
      setTimeout(() => {
        window.location.reload();
      }, 1000)
    }
    else {
      showFailToast(res.data.description)
    }
  }).catch((err)=>{})
}
const yjshow = ref(false)

const pickerValue = ref<Numeric[]>([]);
const onConfirm = ({ selectedValues, selectedOptions }) => {
  yjshow.value = false;
  pickerValue.value = selectedValues;
  if(pickerValue.value.length == 0){
    showFailToast("请选择要移交的房主")
    return;
  }

  exitTeamObj.specialUserId = pickerValue.value[0]
  quitTeam(exitTeamObj).then((res) =>{
    if(res.data.data){
      showSuccessToast("移交队伍成功")
      setTimeout(() => {
        window.location.reload();
      }, 1000)
    }
    else {
      showFailToast(res.data.description)
    }
}).catch((err)=>{})


};
// const teamList = computed(() => props.TeamList || []); //监听组件的传参，传了就显示，没传就隐藏，
// 这么写最重要的还是为了如果父组件没有传递 TeamList，或者传递了 undefined，那么在子组件中直接访问 props.TeamList.length 就会抛出错误。
let teamList = []
const columns = ref([]);
watch(()=>props.TeamList, (newValue, oldValue) => {
  teamList = newValue
  if(teamList.length == 0){
    teamList = []
    return
  }
  teamList.forEach((item:any)=>{
    item.userVOList.forEach((item:any)=>{
      item.tags = JSON.parse(item.tags)
    })
  })
  console.log("new",newValue)
  console.log("old",oldValue)
})
const updateTeam = (team) => {

}
</script>

<template>
  <van-card
      v-for="team in TeamList"
      :desc="team.description"
      :title="team.name"
  >
    <template #bottom>
      <h3>{{"创建时间：" + new Date(team.createTime).toLocaleString("zh-CN", { timeZone: "Asia/Shanghai" })}}</h3>
      <h3>{{"截止时间：" + new Date(team.expireTime).toLocaleString("zh-CN", { timeZone: "Asia/Shanghai" })}}</h3>
      <h3>{{"最大人数：" + team.maxNum}}</h3>
      <h3 v-if="team.status == 0">状态：<van-tag  plain type="success" >公开</van-tag></h3>
      <h3 v-if="team.status == 1">状态：<van-tag  plain type="primary" >私有</van-tag></h3>
      <h3 v-if="team.status == 2">状态：<van-tag  plain type="danger" >加密</van-tag></h3>
      <div v-for="joinuser in team.userVOList" style="display: inline-block;padding: 2rem 2rem 0 1rem;">
          <van-image @click="detailInfo(joinuser,team)"
              round
              width="3rem"
              height="3rem"
              :src="joinuser.avatarUrl"
          />
          <van-tag v-if="joinuser.id==team.userId" plain type="primary">房主</van-tag>
        </div>
    </template>
    <template #footer >

      <van-button size="small" type="primary" @click="router.push({path:'/teamAdd',query:{team: JSON.stringify(team)}})" v-if=" route.path =='/mycreateTeam'">修改信息</van-button>

      <van-button size="small" type="danger" @click="exitTeam(team)" v-if=" route.path =='/mycreateTeam'|| route.path =='/myJoinTeam'">退出队伍</van-button>

      <van-button size="small" type="primary" @click="join(team.id)" v-if="team.status==0 && route.path !='/mycreateTeam' && route.path !='/myJoinTeam'" >加入队伍</van-button>

      <van-button size="small" type="warning" @click="joinpassword(team.id)" v-if="team.status==2 &&route.path !='/mycreateTeam'&& route.path !='/myJoinTeam'">加入队伍</van-button>

    </template>
  </van-card>

  <van-dialog v-model:show="showPicker" title="详细信息">
    <van-cell title="账号" :value="showdetailUser.userAccount"></van-cell>
    <van-cell title="电话" :value="showdetailUser.phone"></van-cell>
    <van-cell title="邮箱" :value="showdetailUser.email"></van-cell>
    <van-cell title="性别" :value="showdetailUser.gender ? '男' : '女'"></van-cell>
    <van-cell title="自我介绍" :value="showdetailUser.profile"></van-cell>
    <van-cell title="标签" >
      <van-tag type="danger" style="margin: 8px 8px 0 0" v-for="tag in showdetailUser.tags" :key="tag" >
        {{tag}}
      </van-tag>
    </van-cell>
  </van-dialog>

  <van-dialog v-model:show="show" title="请输入密码" show-cancel-button @cancel="cancel" @confirm="join(JoinTeamRequest.teamId)">
    <van-field
        label="密码"
        v-model="JoinTeamRequest.password"
        type="password"
        placeholder="请输入密码"
        clearable
    />
  </van-dialog>
<!--  <van-overlay :show="show" class-name="custom-class-name" >-->
<!--    <div class="wrapper" @click.stop >-->
<!--      <div class="block">-->
<!--        <van-field-->

<!--            label="密码"-->
<!--            v-model="JoinTeamRequest.password"-->
<!--            type="password"-->
<!--            placeholder="请输入密码"-->
<!--            clearable-->
<!--        />-->
<!--        <div style="margin: 16px ; text-align: center;">-->
<!--          <van-button type="warning" @click="cancel()" >取消</van-button>-->
<!--          <van-button type="success" @click="join(JoinTeamRequest.teamId)">确认</van-button>-->
<!--        </div>-->
<!--      </div>-->
<!--    </div>-->
<!--  </van-overlay>-->

  <van-popup v-model:show="yjshow" destroy-on-close round position="bottom">
    <van-picker
        title="请选择你要移交的房主"
        :model-value="pickerValue"
        :columns="columns"
        @cancel="yjshow = false"
        @confirm="onConfirm"
    />
  </van-popup>

  <van-empty image="search" v-if="teamList.length==0" description="搜索结果为空" />

</template>

<style scoped>

.wrapper {

  display: flex;
  align-items: center;
  justify-content: center;
  height: 80%;
}

.block {
  width: 80%;
  height: 18%;
  background: #fff;
}

.van-field {
  margin-bottom: 10px;
}

.van-button {
  margin-right: 20px;
}

.van-button:last-child {
  margin-right: 0;
}
</style>

